'use strict';

const Service = require('egg').Service;
const qiniu = require('qiniu');

class QiniuService extends Service {
  // 生成上传凭证
  getUploadToken() {
    const { accessKey, secretKey, bucket } = this.config.qiniu;
    const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
    const options = {
      scope: bucket,
      expires: 3600 // 1小时有效期
    };
    const putPolicy = new qiniu.rs.PutPolicy(options);
    return putPolicy.uploadToken(mac);
  }

  // 流式上传文件
  async uploadStream(stream, key) {
    const config = new qiniu.conf.Config();
    const formUploader = new qiniu.form_up.FormUploader(config);
    const putExtra = new qiniu.form_up.PutExtra();

    return new Promise((resolve, reject) => {
      formUploader.putStream(this.getUploadToken(), key, stream, putExtra, 
        (err, ret) => {
          if (err) return reject(err);
          resolve({
            key: ret.key,
            hash: ret.hash,
            url: this.getFileUrl(ret.key)
          });
        });
    });
  }

  // 获取文件访问URL
  getFileUrl(key) {
    const { cdnDomain } = this.config.qiniu;
    const bucketManager = new qiniu.rs.BucketManager(
      new qiniu.auth.digest.Mac(this.config.qiniu.accessKey, this.config.qiniu.secretKey),
      new qiniu.conf.Config()
    );
    return bucketManager.publicDownloadUrl(cdnDomain, key);
  }
}

module.exports = QiniuService;